package com.ruoyi.web.controller.lowcode;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.CacheNames;
import com.ruoyi.common.core.validate.*;
import com.ruoyi.common.utils.redis.CacheUtils;
import com.ruoyi.lowcode.config.OpenApiConfig;
import com.ruoyi.lowcode.domain.bo.*;
import com.ruoyi.lowcode.domain.vo.*;
import com.ruoyi.lowcode.utils.POIUtils;
import com.ruoyi.lowcode.utils.WordUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import lombok.RequiredArgsConstructor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.lowcode.service.ILcModelService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 模型
 *
 * @author ruoyi
 * @date 2023-09-30
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/lowcode/model")
public class LcModelController extends BaseController {

    private final ILcModelService iLcModelService;

    @Resource
    private OpenApiConfig openApiConfig;

    @Resource
    private WordUtils wordUtils;

    /**
     * 获取模型子模型
     *
     * @param modelId
     * @return
     */
    @GetMapping("/getModelSon/{modelId}")
    public R getModelSon(@NotNull(message = "模型id不能为空")
                             @PathVariable Long modelId){
        return R.ok(iLcModelService.getModelSon(modelId));
    }

    /**
     * 模型插入单条数据
     *
     * @param modelRowBo
     * @return
     */
    @PostMapping("/addOrUpdateModelRow")
    public R addOrUpdateModelRow(@Validated(AddOrUpdateGroup.class) @RequestBody ModelRowBo modelRowBo) throws ClassNotFoundException {
        return R.ok(iLcModelService.addOrUpdateModelRow(modelRowBo));
    }

    /**
     * 模型删除单条数据
     *
     * @param modelRowBo
     * @return
     */
    @PostMapping("/deleteModelRow")
    public R deleteModelRow(@Validated(DeleteGroup.class) @RequestBody ModelRowBo modelRowBo) throws ClassNotFoundException {
        return R.ok(iLcModelService.deleteModelRow(modelRowBo));
    }

    /**
     * 查询模型列表
     */
    @SaCheckPermission("lowcode:model:list")
    @GetMapping("/list")
    public TableDataInfo<LcModelVo> list(LcModelBo bo, PageQuery pageQuery) {
        return iLcModelService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询模型列表
     *
     * @param bo
     * @return
     */
    @SaCheckPermission("lowcode:model:list")
    @GetMapping("/queryList")
    public R<List<LcModelVo>> queryList(LcModelBo bo){
        return R.ok(iLcModelService.queryList(bo));
    }

    /**
     * 获取模型搜索参数，列表参数信息
     *
     * @param modelId
     * @return
     */
    @GetMapping("/table/{modelId}")
    public R<ModelInfoVo> getTableModel(@NotNull(message = "模型id不能为空")
                              @PathVariable Long modelId){
        return R.ok(iLcModelService.getTableModel(modelId));
    }

    /**
     * 获取模型字段
     *
     * @param modelId
     * @return
     */
    @GetMapping("/getFormModelField/{modelId}")
    public List<FormModelFieldVo> getFormModelField(@NotNull(message = "模型id不能为空")
                                                    @PathVariable Long modelId){
        return iLcModelService.getFormModelField(modelId);
    }

    /**
     * 下载接口文档
     *
     * @param modelId
     */
    @PostMapping("/downloadDocument/{modelId}")
    public void downloadDocument(@NotNull(message = "主键不能为空")
                                     @PathVariable Long modelId, HttpServletResponse response) throws IOException {
        // 格式化数据
        ModelInfoVo modelInfo = iLcModelService.getTableModel(modelId);
        LcModelVo model =  modelInfo.getModel();
        model.setUrl(openApiConfig.getUrlPrefix() + model.getModelId());
        modelInfo.setModel(model);
        wordUtils.exportOpenApiWord(modelInfo, response);
    }

    /**
     * 根据模型id获取数据列表
     *
     * @param selectListModelBo
     * @return
     */
    @PostMapping("/selectListByModel")
    public TableDataInfo<Map<String, Object>> selectListByModel(@Validated() @RequestBody SelectListModelBo selectListModelBo){
        try {
            return iLcModelService.selectListByModel(selectListModelBo);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询失败，模型id为" + selectListModelBo.getModelId() + "。原因" + e.getMessage());
        }
        return TableDataInfo.build();
    }

    /**
     * 根据模型id导出excel
     *
     * @param params
     * @param response
     */
    @PostMapping("/exportByModel/{modelId}")
    public void exportByModel(@PathVariable String modelId, @RequestParam Map<String, Object> params, HttpServletResponse response) throws ClassNotFoundException, JSQLParserException, IOException {
        SelectListModelBo selectListModelBo = new SelectListModelBo();
        selectListModelBo.setModelId(Long.parseLong(modelId));
        selectListModelBo.setParams(params);
        POIUtils.exportExcel(iLcModelService.exportByModel(selectListModelBo), response);
    }

    /**
     * 导出模型列表
     */
//    @SaCheckPermission("lowcode:model:export")
//    @Log(title = "模型", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(LcModelBo bo, HttpServletResponse response) {
//        List<LcModelVo> list = iLcModelService.queryList(bo);
//        ExcelUtil.exportExcel(list, "模型", LcModelVo.class, response);
//    }

    /**
     * 获取模型详细信息
     *
     * @param modelId 主键
     */
    @SaCheckPermission("lowcode:model:query")
    @GetMapping("/{modelId}")
    public R<LcModelVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long modelId) {
        return R.ok(iLcModelService.queryById(modelId));
    }

    /**
     * 初始化模型字段
     *
     * @param modelId
     * @return
     */
    @SaCheckPermission("lowcode:model:edit")
    @Log(title = "模型", businessType = BusinessType.UPDATE)
    @GetMapping("/initializationField/{modelId}")
    public R<Boolean> initializationField(@NotNull(message = "主键不能为空")
                                @PathVariable Long modelId) {
        return R.ok(iLcModelService.initializationField(modelId));
    }

    /**
     * 新增模型
     */
    @SaCheckPermission("lowcode:model:add")
    @Log(title = "模型", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody LcModelBo bo) {
        return toAjax(iLcModelService.insertByBo(bo));
    }

    /**
     * 修改模型
     */
    @SaCheckPermission("lowcode:model:edit")
    @Log(title = "模型", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody LcModelBo bo) {
        return toAjax(iLcModelService.updateByBo(bo));
    }

    /**
     * 删除模型
     *
     * @param modelIds 主键串
     */
    @SaCheckPermission("lowcode:model:remove")
    @Log(title = "模型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{modelIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] modelIds) {
        return toAjax(iLcModelService.deleteWithValidByIds(Arrays.asList(modelIds), true));
    }
}
